package com.eight.vote.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * 生成、解析USer Token
 */
public class JWTUtil {
    // token加密时使用的秘钥，一旦得到此秘钥也就可以伪造token了
    private static String secretKey = "ZZKJwtTokenKey";
    private final static long KEEP_TIME = 60 * 60 * 24 * 24*1000;

    private static Algorithm tokenAlgorithm = null; //可复用的加密算法
    private static JWTVerifier tokenVerifier = null;//可复用的token解析器
    //usertype
    public static final String USER_TYPE=new String("user");
    public static final String ADMIN_TYPE=new String("admin");

    //init
    static {
        tokenAlgorithm = Algorithm.HMAC256(secretKey);
        tokenVerifier = JWT.require(tokenAlgorithm).withIssuer("zzk").build();
    }

    public static String generateToken(String userid, String usertype, String issuer) {
        String token = createJwt(userid, usertype, issuer);
        return token;
    }

    public static String generateToken(String userid,String usertype){
        String token = createJwt(userid, usertype, "");
        return token;
    }

    /**
     *解析token获取userid
     */
    public static String getUserId(String token){
        String userid = tokenVerifier.verify(token).getClaim("userid").asString();
        return userid;
    }

    /**
     * 解析token获取usertype
     */
    public static String getUserType(String token){
        String usertype = tokenVerifier.verify(token).getClaim("usertype").asString();
        return usertype;
    }
    //判断token是否有效
    public static boolean isExpiration(String token){
        try {
            DecodedJWT verify = tokenVerifier.verify(token);
            return true;
        }catch (JWTVerificationException exception){
            return false;
        }
    }

    /**
     * 调用java-jwt生成token
     */
    private static  String createJwt(String userid, String usertype, String issuer){
        if ("".equals(issuer) || issuer == null){//默认发行人为zzk
            issuer = "zzk";
        }
        String token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + KEEP_TIME)) //失效时间
                .withClaim("userid",userid)//用户id
                .withClaim("usertype",usertype)//用户类型
                .withIssuer(issuer) //发行人
                .sign(tokenAlgorithm);//加密算法

        return token;
    }

}
